package com.superfish.cutieshop.http;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.superfish.cutieshop.BaseApp;
import com.superfish.cutieshop.utils.LogTest;
import com.superfish.cutieshop.utils.UID;

import java.util.List;

/**
 * http请求操作类
 *
 * @author JackWu
 */
public class HttpStores {
    private static HttpStores mHttpStores;
    private HttpUtils mHttp;


    private HttpStores() {
        mHttp = new HttpUtils();
        mHttp.configCurrentHttpCacheExpiry(2000);//缓存两秒
    }

    public synchronized static HttpStores getInstense() {
        if (mHttpStores == null) {
            mHttpStores = new HttpStores();
        }
        return mHttpStores;
    }

    /**
     * 获取http引用
     **/
    public HttpUtils getHttp() {
        return mHttp;
    }

    public void get(final ZokeParams params) {
        handleMethod(params, HttpRequest.HttpMethod.GET, true);
    }

    /**
     * 没有UID时调用，会传递没有UID的token
     *
     * @param params
     */
    public void login(final ZokeParams params) {
        handleMethod(params, HttpRequest.HttpMethod.POST, false);
    }

    public void post(final ZokeParams params) {
        handleMethod(params, HttpRequest.HttpMethod.POST, true);
    }


    private void handleMethod(final ZokeParams params, HttpRequest.HttpMethod method, boolean hasUid) {
        //设置Headers
        if (hasUid) {
            //登陆后
            params.setHeader("token", BaseApp.getNextUidToken());
        } else {
            //未登陆
            try {
                params.setHeader("openid", UID.encrypt(BaseApp.getDeviceId()));
            } catch (Exception e) {
            }
        }
        List<RequestParams.HeaderItem> list = params.getHeaders();
        //打印Header
        if (list != null)
            for (RequestParams.HeaderItem item : list) {
                LogTest.wlj("Header===" + item.header.getName() + ":" + item.header.getValue());
            }
        mHttp.send(method, params.getUrl(), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                params.setResult(responseInfo);
                CallBackStores.getCallback().notifySuccess(params);
            }

            @Override
            public void onFailure(HttpException e, String s) {
                HttpError erro = new HttpError();
                erro.exception = e;
                erro.s = s;
                params.setResult(erro);
                CallBackStores.getCallback().notifyFaile(params);
            }
        });
    }


}
